package com.hrb.douban.activtity;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hrb.commonsdk.okhttp.listener.DisposeDataListener;
import com.hrb.commonsdk.okhttp.request.RequestParams;
import com.hrb.douban.CustomApplication;
import com.hrb.douban.OnItemClickListener;
import com.hrb.douban.R;
import com.hrb.douban.activtity.base.BaseActivity;
import com.hrb.douban.adapter.DirectorAdapter;
import com.hrb.douban.constant.HttpConstants;
import com.hrb.douban.mview.CollectBtn;
import com.hrb.douban.network.RequestCenter;
import com.hrb.douban.record.DirectorRecord;
import com.hrb.douban.record.FilmDetailRecord;
import com.hrb.douban.record.PersonRecord;
import com.hrb.douban.utils.ACache;
import com.hrb.douban.utils.DateUtil;
import com.hrb.douban.utils.ImageUtil;
import com.hrb.douban.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FilmDetailsActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG="FilmDetailsActivity";

    @BindView(R.id.film_detail)
    TextView filmDetail;
    @BindView(R.id.film_detail_back_icons)
    ImageView backIcons;
    @BindView(R.id.film_detail_header)
    RelativeLayout filmDetailHeader;
    @BindView(R.id.film_cover)
    ImageView filmCover;
    @BindView(R.id.f_title)
    TextView fTitle;
    @BindView(R.id.f_director)
    TextView fDirector;
    @BindView(R.id.f_cast)
    TextView fCast;
    @BindView(R.id.f_rate)
    TextView fRate;
    @BindView(R.id.f_year)
    TextView fYear;
    @BindView(R.id.film_detail_header_top)
    LinearLayout filmDetailHeaderTop;
    @BindView(R.id.f_rate_l)
    TextView fRateL;
    @BindView(R.id.f_rate_c)
    TextView fRateC;
    @BindView(R.id.f_rate_r)
    TextView fRateR;
    @BindView(R.id.film_detail_message)
    TextView filmDetailMessage;
    @BindView(R.id.film_detail_category_box)
    LinearLayout filmDetailCategoryBox;
    @BindView(R.id.film_detail_recycler)
    RecyclerView filmDetailRecycler;
    @BindView(R.id.collect_button)
    CollectBtn collectButton;
    private FilmDetailRecord record;
    private DirectorAdapter adapter;
    private ACache cacheUtil;
    private ArrayList<FilmDetailRecord> filmlist=new ArrayList<FilmDetailRecord>();
    private ArrayList<FilmDetailRecord> collectlist=new ArrayList<FilmDetailRecord>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_film_details);
        ButterKnife.bind(this);
        backIcons.setOnClickListener(this);
        String id = getIntent().getStringExtra("id");
        LinearLayoutManager layoutManager = new LinearLayoutManager(CustomApplication.getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        filmDetailRecycler.setLayoutManager(layoutManager);
        requestData(null, id);
        cacheUtil=ACache.get(CustomApplication.getContext());
        Log.d(TAG,"oncreate");

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG,"onNewIntent");
        String id = getIntent().getStringExtra("id");
        LinearLayoutManager layoutManager = new LinearLayoutManager(CustomApplication.getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        filmDetailRecycler.setLayoutManager(layoutManager);
        requestData(null, id);
        cacheUtil=ACache.get(CustomApplication.getContext());
    }

    private void intLayout() {
        //初始化
        if((ArrayList<FilmDetailRecord>)cacheUtil.getAsObject("filmlistCollect")!=null){
            collectlist=(ArrayList<FilmDetailRecord>)cacheUtil.getAsObject("filmlistCollect");
        }
//        收藏列表是否有此记录
        Iterator<FilmDetailRecord> iterator=collectlist.iterator();
        while(iterator.hasNext()){
            FilmDetailRecord p=iterator.next();
            if(record!=null&&record.getId()!=null&&record.getId().equals(p.getId())){
                collectButton.setmState(true);
            }
        }
        collectButton.setmCollectBtnChangeListener(new CollectBtn.CollectBtnChangeListener(){
            @Override
            public void onClick(boolean flag) {
                ToastUtil.show(flag?"已收藏":"取消收藏");
                if((ArrayList<FilmDetailRecord>)cacheUtil.getAsObject("filmlistCollect")!=null){
                    collectlist=(ArrayList<FilmDetailRecord>)cacheUtil.getAsObject("filmlistCollect");
                }
                if(flag){
                    record.setAddTime(DateUtil.getDate());
                    Iterator<FilmDetailRecord> iterator=collectlist.iterator();
                    while(iterator.hasNext()){
                        FilmDetailRecord p=iterator.next();
                        if(record!=null&&record.getId()!=null&&record.getId().equals(p.getId())){
                            iterator.remove();
                        }
                    }
                    collectlist.add(0,record);
                    cacheUtil.put("filmlistCollect",collectlist,1000*60);
                }else{
                    Iterator<FilmDetailRecord> iterator=collectlist.iterator();
                    while(iterator.hasNext()){
                        FilmDetailRecord p=iterator.next();
                        if(record!=null&&record.getId()!=null&&record.getId().equals(p.getId())){
                            iterator.remove();
                        }
                    }
                }
            }
        });
    }

    private void requestData(RequestParams params, String id) {
        RequestCenter.getRequest(HttpConstants.DETAILSROOT + id, params, FilmDetailRecord.class, new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                try {
                    if (responseObj != null) {
                        record = (FilmDetailRecord) responseObj;
                        if((ArrayList<FilmDetailRecord>)cacheUtil.getAsObject("filmlist")!=null){
                           filmlist=(ArrayList<FilmDetailRecord>)cacheUtil.getAsObject("filmlist");
                        }
                        record.setAddTime(DateUtil.getDate());
                        Iterator<FilmDetailRecord> iterator=filmlist.iterator();
                        while(iterator.hasNext()){
                            FilmDetailRecord p=iterator.next();
                            if(record!=null&&record.getId()!=null&&record.getId().equals(p.getId())){
                                iterator.remove();
                            }
                        }
                        filmlist.add(0,record);
                        cacheUtil.put("filmlist",filmlist,1000*60);
                        Glide.with(CustomApplication.getContext()).load(record.getImages().getLarge()).centerCrop().into(filmCover);
                        //ImageUtil.loadIntoUseFitWidth(record.getImages().getLarge(), filmCover);
                        fTitle.setText(record.getTitle());
                        String dirStr = "";
                        String castStr = "";
                        for (FilmDetailRecord.DirectorsBean der : record.getDirectors()) {
                            dirStr += der.getName() + "/";
                            ;
                        }
                        for (FilmDetailRecord.CastsBean cast : record.getCasts()) {
                            castStr += cast.getName() + "/";
                        }
                        fDirector.setText("导演:" + dirStr.substring(0, dirStr.lastIndexOf("/")));
                        fRate.setText("豆瓣评分 : " + record.getRating().getAverage());
                        fCast.setText("演员 : " + castStr.substring(0, castStr.lastIndexOf("/")));
                        fYear.setText("上映年份 : " + record.getYear());
                        fRateL.setText(record.getCollect_count() + "");
                        fRateC.setText(record.getWish_count() + "");
                        fRateR.setText(record.getRatings_count() + "");
                        //剧情简介
                        filmDetailMessage.setText(record.getSummary());
                        //标签
                        boolean first = true;
                        for (String category : record.getGenres()) {
                            TextView tv = new TextView(CustomApplication.getContext());
                            tv.setText(category);
                            tv.setTextSize(12);
                            tv.setTextColor(CustomApplication.getContext().getResources().getColor(R.color.color_666666));
                            tv.setPadding(10, 2, 0, 2);
                            tv.setBackgroundResource(R.drawable.category_shape);
                            if (!first) {
                                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                lp.setMargins(6, 0, 0, 0);
                                tv.setLayoutParams(lp);
                            } else {
                                first = false;
                            }
                            filmDetailCategoryBox.addView(tv);
                        }
                        List<DirectorRecord> directorRecordList = new ArrayList<DirectorRecord>();
                        for (FilmDetailRecord.DirectorsBean directorsBean : record.getDirectors()) {
                            DirectorRecord directorRecord = new DirectorRecord();
                            directorRecord.setId(directorsBean.getId());
                            directorRecord.setAlt(directorsBean.getAlt());
                            directorRecord.setName(directorsBean.getName());
                            directorRecord.setAvatars(directorsBean.getAvatars().getLarge());
                            directorRecord.setRole("导演");
                            directorRecordList.add(directorRecord);
                        }
                        for (FilmDetailRecord.CastsBean castsBean : record.getCasts()) {
                            DirectorRecord directorRecord = new DirectorRecord();
                            directorRecord.setId(castsBean.getId());
                            directorRecord.setAlt(castsBean.getAlt());
                            directorRecord.setName(castsBean.getName());
                            directorRecord.setAvatars(castsBean.getAvatars().getLarge());
                            directorRecord.setRole("演员");
                            directorRecordList.add(directorRecord);
                        }
                        adapter = new DirectorAdapter(directorRecordList);
                        adapter.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                Intent intent = new Intent(getApplicationContext(), PersonDetailActivity.class);
                                intent.putExtra("id", adapter.getDirectors().get(position).getId());
                                startActivityForResult(intent, 101);
                            }

                            @Override
                            public void onCategoryClick(View view, String category) {

                            }
                        });
                        filmDetailRecycler.setAdapter(adapter);
                    }
                    //为收藏按钮添加操作
                    intLayout();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {

            }
        });
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.film_detail_back_icons:
               /* Intent backIntent = new Intent(this, MainActivity.class);
                backIntent.putExtra("name", 1);
                //FilmDetailsActivity.this.setResult(ConstantCode.resultCode, backIntent);
                startActivity(backIntent);*/
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            /*Intent backIntent = new Intent(this, MainActivity.class);
            backIntent.putExtra("name", 1);
            //FilmDetailsActivity.this.setResult(ConstantCode.resultCode, backIntent);
            startActivity(backIntent);*/
            finish();

        }
        return true;

    }
}
